<template>
  <!-- 不合格标本记录子组件 -->
  <div id="unqSpecRec">
    <Breadcrumb content="不合格标本" v-if="showBreadCrumbTag === true" />
    <GoBack :content="'不合格标本'" v-if="showBreadCrumbTag === false" @closeDrawer="closeDrawer" :backUrl="url"></GoBack>
    <div class="bodyContent">
      <Splitpanes horizontal class="area">
        <Pane size="50">
          <div>
            <vxe-toolbar perfect>
              <template #buttons>
                <span>条码号：</span>
                <vxe-input v-model="form.reqNo" clearable @keyup="handleSearch"></vxe-input>
                <span class="padding-lr-xs">
                  <vxe-button type="text" content="新增" class-name="padding-lr-xs" class="button-blue padding-lr-xs" @click="saveUnqualified" />
                </span>
                <span class="padding-lr-xs">
                  <vxe-button type="text" content="保存" class-name="padding-lr-xs" class="button-blue padding-lr-xs" @click="save" />
                </span>
                <span class="padding-lr-xs">
                  <vxe-button type="text" content="删除" class-name="padding-lr-xs" class="button-red padding-lr-xs" @click="handleDelete(currentUnqSpecRec.id)" />
                </span>
              </template>
            </vxe-toolbar>
          </div>
          <div class="unqApplicationRecTable" style="height: calc(100% - 30px)">
            <vxe-table ref="unqApplicationRecTable" :loading="loading" border height="100%" :data="unqApplicationRecList" @current-change="unqApplicationRecRowClick" :row-config="{ isCurrent: true, isHover: true }" :edit-config="{ trigger: 'click', mode: 'cell', showStatus: false, showIcon: false }" :keyboard-config="{
              isArrow: true,
            }" resizable show-overflow>
              <vxe-column type="seq" title="序号" width="30"></vxe-column>
              <vxe-column field="operatorTime" title="登记时间" width="120">
              </vxe-column>
              <vxe-column field="illustrate" title="不合格标本原因">
              </vxe-column>
              <vxe-column field="contactName" title="临床联系人" width="200" :edit-render="{ autofocus: '.vxe-input--inner' }">
                <template #edit="{ row, rowIndex }">
                  <VxePulldownSelectionWithNa style="width: 100%" :isChild="true" :childIndex="rowIndex" :url="'/api/user/getUserInfoList'" @confirmClick="SelectRowClick" :tableColumn="[
                { type: 'seq', title: '#', width: '30px' },
                { field: 'realname', title: '姓名' },
                { field: 'username', title: '编码' }
              ]" :aimKeys="[
                { aimKey: 'contactName', rowKey: 'realname' },
                { aimKey: 'contactCode', rowKey: 'username' }
              ]" :displayTexts="['userName']" :displayTextObj="row.contactName ? row.contactName : ''" />
                </template>
              </vxe-column>
              <vxe-column field="contactTime" title="联系时间" width="450" :edit-render="{ autofocus: '.vxe-input--inner' }">
                <template #default="{ row }">
                  {{ row.contactTime }}
                </template>
                <template #edit="{ row }">
                  <vxe-input v-model="row.contactTime" type="datetime"></vxe-input>
                </template>
              </vxe-column>
              <vxe-column field="handler" title="处理人" width="80">
              </vxe-column>
              <vxe-column field="handleInfo" title="处理意见" show-overflow-tooltip>
              </vxe-column>
              <vxe-column field="handleTime" title="处理时间" width="120">
              </vxe-column>
            </vxe-table>
          </div>
        </Pane>
        <Pane size="50">
          <UnqualifiedSpecRec ref="unqualifiedSpecRecRef" @saveReasons="saveReasons" />
        </Pane>
      </Splitpanes>
    </div>
  </div>
</template>
<script lang="ts" setup>
import Breadcrumb from '@/components/Breadcrumb.vue'; //面包屑
import GoBack from '@/components/GoBack.vue'; //返回组件
import { ref, reactive, getCurrentInstance, onMounted, ObjectDirective } from 'vue';
import { VxeMessage, VxeNotifyType } from '@/utils/CommonMessage';
import { IsEmpty, formatDateTime, TimePickerOpts } from '@/utils/common';
import { Splitpanes, Pane } from 'splitpanes';
import UnqualifiedSpecRec from '@/components/UnqualifiedSpecRec.vue';
import { AppStore } from '@/stores/store';
import VxePulldownSelectionWithNa from '@/components/VxePulldownSelectionWithNa.vue';

let { proxy }: any = getCurrentInstance();
let store = AppStore();
// 方法定义区 =============
defineExpose({ getSample, init });
let showBreadCrumbTag = ref(true); //当为true时显示的是普通面包屑 false显示的是返回组件
let url = ref(''); //抽屉要返回的路由地址

function init(row: any, row2: any) {
  url.value = row;
  showBreadCrumbTag.value = !row2;
}

// 关闭抽屉
function closeDrawer() {
  showBreadCrumbTag.value = true; //恢复成面包屑
  proxy.$emit('closeDrawer');
}

let loading = ref(false);
let unqualifiedSpecRecRef: any = ref(null); //复查
let currentUnqSpecRec = ref({}) as any; //当前选中行
let unqApplicationRecList = reactive([]); //列表
let currentRowIndex = 0;
let form = reactive({
  id: '',
  reqMainId: '',
  reqNo: '',
  patTypeNa: '',
  patNa: '',
  sex: '',
  age: '',
  sampleType: '',
  testPurpose: ''
});
let formRules = {
  visitTypeId: [{ required: true, message: '请选择病人来源' }]
};

//回车事件
function handleSearch(e: any) {
  if (e.$event.code == 'Enter') {
    if (IsEmpty(e.value)) {
      VxeMessage('请输入条码号', VxeNotifyType.error);
      return;
    }
    getReqMainInfo(e.value);
  }
}

function getReqMainInfo(e: any) {
  loading.value = true;
  const url = '/lab/reqMain/findReqMainByReqNo';
  const data = {
    reqNo: e
  };
  proxy.$http
    .get(url, { params: data })
    .then((res: any) => {
      if (res.data.length > 0) {
        Object.assign(form, res.data[0]);
        saveUnqualified();
      } else {
        //扫码上机
        insertMaininfoByReqNo(e.value);
      }
    })
    .catch((err) => {
      loading.value = false;
      VxeMessage('数据请求异常', VxeNotifyType.error);
    });
}
function getInfoList(reqNo) {
  loading.value = true;
  const url = '/lab/reqMain/findReqMainByReqNo';
  const data = {
    reqNo: reqNo
  };
  proxy.$http
    .get(url, { params: data })
    .then((res: any) => {
      if (res.data.length > 0) {
        Object.assign(form, res.data[0]);
        saveUnqualified();
      } else {
        VxeMessage('数据未同步', VxeNotifyType.error);
      }
    })
    .catch((err) => {
      loading.value = false;
      VxeMessage('数据请求异常', VxeNotifyType.error);
    });
}
//扫码上机
function insertMaininfoByReqNo(reqNo: any) {
  const url = '/lab/maininfo/insertMaininfoBySpecimen';
  const data = {
    reqNo: reqNo
  };
  proxy.$http
    .post(url, data)
    .then((res: any) => {
      if (res.status.code === 200) {
        getInfoList(reqNo);
      } else {
        VxeMessage(res.status.msg, VxeNotifyType.error);
      }
      loading.value = false;
    })
    .catch((err) => {
      loading.value = false;
    });
}

function getSample(refSpecimenData: any) {
  Object.assign(form, refSpecimenData);
  findUnqSpecRecBySpecId();
}

// 根据reqMainId获取列表
function findUnqSpecRecBySpecId() {
  unqApplicationRecList.length = 0;
  loading.value = true;
  const url = '/lab/req/unqualified/getUnqualified';
  const data = {
    reqNo: form.reqNo,
    sourceType: 'req'
  };
  proxy.$http
    .get(url, { params: data })
    .then((res: any) => {
      unqApplicationRecList.push(...res.data);
      if (unqApplicationRecList.length > 0) {
        unqApplicationRecRowClick({ row: unqApplicationRecList[0], rowIndex: 0 });
        unqualifiedSpecRecRef.value.getDetil(unqApplicationRecList[0].id);
      }
      loading.value = false;
    })
    .catch((err) => {
      loading.value = false;
      VxeMessage('数据请求异常', VxeNotifyType.error);
    });
}

/**下拉选中行事件 */
function SelectRowClick(e) {
  e.aimKeys.forEach((r) => {
    unqApplicationRecList[e.childIndex][r.aimKey] = e.row[r.rowKey];
  });
}
//新增调用保存一条主记录
function saveUnqualified() {
  if (IsEmpty(form.id)) {
    if (IsEmpty(form.reqNo)) {
      VxeMessage('该条形码没有申请信息', VxeNotifyType.error);
    } else {
      getReqMainInfo(form.reqNo);
    }
    return;
  }
  const params = {
    reqNo: form.reqNo,
    sourceType: 'req'
  };
  const url = '/lab/req/unqualified/saveUnqualified';
  proxy.$http
    .post(url, params)
    .then((res: any) => {
      findUnqSpecRecBySpecId();
    })
    .catch((err: any) => {
      VxeMessage(err, VxeNotifyType.error);
    });
}

//保存
function save() {
  //获取当前行的信息
  const data = (proxy.$refs.unqApplicationRecTable as any).getCurrentRecord();
  unqualifiedSpecRecRef.value.saveDetil(data);
}

//删除
function handleDelete(id) {
  proxy
    .$confirm('确认删除此项？', '提示', {
      cancelButtonClass: 'cancel-button',
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    })
    .then(() => {
      const url = '/lab/req/unqualified/deleteUnqualified';
      proxy.$http
        .get(url, { params: { id: id } })
        .then((res: any) => {
          findUnqSpecRecBySpecId();
          VxeMessage('删除成功', VxeNotifyType.success);
        })
        .catch((err) => {
          VxeMessage('删除失败', VxeNotifyType.error);
        });
    })
    .catch((err) => {
      console.log(err);
    });
}
// 行点击事件
function unqApplicationRecRowClick({ row, rowIndex }) {
  if (IsEmpty(row)) {
    saveUnqualified();
    return;
  }
  currentRowIndex = rowIndex;
  currentUnqSpecRec = row;
  (proxy.$refs.unqApplicationRecTable as any).setCurrentRow(row);
  unqualifiedSpecRecRef.value.getDetil(row.id);
}

//返回不合格原因中文字符串
function saveReasons(illustrate) {
  unqApplicationRecList[currentRowIndex].illustrate = illustrate;
}
//监听回车事件
function keyup(e: any) {
  if (e.$event.key == 'Enter') {
    addWklt();
  }
}

function addWklt() {
  //?条码号为空，不添加
  if (IsEmpty(form.reqNo)) {
    form.reqNo = '';
    (proxy.$refs.scanInputRef as any).focus();
    return;
  }
}

// #endregion
</script>
<style lang="scss" scoped>
#unqSpecRec {
  height: 100%;
  .bodyContent {
    height: calc(100% - 60px);
    .area {
      background-color: $base-white;
    }
  }

  :deep(.el-descriptions .el-descriptions-item__label) {
    text-align: left;
  }
}
</style>
